{% extends 'bootstrap_children.html' %}
{% block self_head %}
<!-- ACE Editor -->   
<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<link href="/static/bootstrap/dist/css/bootstrap-multiselect.css" rel="stylesheet">
<script src="/static/bootstrap/dist/js/bootstrap-multiselect.js"></script>
<style type="text/css">
	#project_local_command {
		/* position: absolute; */
	width: 100%;
	height: 400px;
   }
</style>
{% endblock %}
{% block content %}
<div id="page-wrapper">
	<div class="row">
		<div class="col-lg-12">
			<h1 class="page-header">
				<i class="fa  fa-wrench"></i> 项目配置中心
			</h1>
		</div>
		<!-- /.col-lg-12 -->
	</div>
	<div class="row">
		<div class="col-lg-12">
			<div class="panel panel-default">
				<div class="panel-heading">
					<i class="fa  fa-plus"></i> 添加项目
				</div>
				<div class="panel-body">
					<div class="row">
						<div class="col-lg-6">
							<legend>
								<i class="fa  fa-paper-plane"></i> 部署服务器
							</legend>
							<form role="form" method="post" id="add_deploy_project">
								{% csrf_token %}
								<div class="form-group">
									<label><font color='red'>* </font>产品线名称</label> 
									<select class="form-control" id="project_id"  onchange="javascript:oBtProjectSelect();" required>
										<option selected="selected" name="project_id">请选择产品线</option>
										{% for ds in baseAssets.project %}
											<option value="{{ds.id}}" name="project_id">{{ds.project_name}}</option>
										{% endfor %}
									</select>									
									<p class="help-block">例如：opsmanage</p>
								</div>
								<div class="form-group">
									 <label><font color='red'>* </font>业务类型</label>
									 <select class="form-control" name="project_service" id="project_service" onchange="javascript:oBtServiceSelect('service','server');" required>
									   		<option selected="selected" value="">请选择一个类型</option>								   							
									</select>
								</div>
								<div class="form-group">
									 <label><font color='red'>* </font>项目名称</label>
									 <input class="form-control" id="project_name" required>
								</div>																	
								<div class="form-group">
									<label><font color='red'>* </font>项目环境</label> 
									<select class="form-control" id="project_env" name="project_env" onchange="javascript:oBtEnvType();" required>
										<option selected="selected" value="">请选择项目环境</option>
										<option value="sit" name="project_env">测试环境</option>
										<option value="qa" name="project_env">预生产环境</option>
										<option value="uat" name="project_env">生产环境</option>
									</select>
								</div>																								
								<div class="form-group">
									<label><font color='red'>* </font>远程仓库类型</label> 
									<select class="form-control" id="project_repertory" name="project_repertory"  onchange="javascript:oBtRepoType();" required>
										<option selected="selected" value="">请选择仓库类型</option>
										<option value="git" name="project_repertory">Git</option>
										<option value="svn" name="project_repertory">Svn</option>
									</select>
								</div>
								<div class="form-group">
									<label><font color='red'>* </font>仓库地址</label> 
									<input class="form-control" id="project_address" name="project_address" required>
									<p class="help-block">例如：git@gitlab.veredholdings-inc.com:fanglianchao/qw_cmdb.git</p>
								</div>
								<div class="form-group" style="display: none;" id="repo_type">
									<label>SVN账户/密码<i class="fa fa-info-circle"
										data-toggle="tooltip" title="选择svn的账户密码"></i></label>
									<div class="form-inline from-group">
										<input type="text" class="form-control"
											id="project_repo_user" placeholder="请输入账户"> <input
											type="text" class="form-control" id="project_repo_passwd"
											placeholder="请输入密码">
									</div>
								</div>
								<div class="form-group">
									<label><font color='red'>* </font>分支/Tag上线<i class="fa fa-info-circle" data-toggle="tooltip" title="选择用branch还是tag作为版本控制"></i></label> 
									<select class="form-control" id="project_model" name="project_model" required>
										<option selected="selected" value="">选择上线版本控制类型</option>
										<option value="branch" name="project_model">Branch</option>
										<option value="tag" name="project_model">Tag</option>
                                        <option value="trunk" name="project_model">Trunk</option>
									</select>
								</div>
								<div class="form-group" >			 		             
									<label ><font color='red'>* </font>语言类型: </label>	
									<div class="btn-group btn-group-sm">
										<button type="button" class="btn btn-default" onclick="setCompileMode('compile')"><a>编译型</a></button>
										<button type="button" class="btn btn-default" onclick="setCompileMode('noncompile')"><a>非编译型</a></button>
									</div>
								</div> 
								<div  id="compile" style="display: none;">
									<div class="form-group" >
										<label>编译命令<i class="fa fa-info-circle" data-toggle="tooltip" title="写入编译命令"></i></label>
										<div id="project_local_command" name="project_local_command" class="ace_editor"></div>								
									</div>
									<div class="form-group">
										<label>代码发布目录<i class="fa fa-info-circle" data-toggle="tooltip" title="真实被同步代码的目录"></i></label> 
										<input class="form-control" name="project_dir" value="{{project_dir}}release/" id="project_dir" required pattern="^/.*/$" title="正确格式：/path/" disabled>
									</div>	
								</div>		
								<div class="form-group">
									<label><font color='red'>* </font>源代码存放地址</label> 
									<input class="form-control" id="project_repo_dir" name="project_repo_dir" value="{{project_dir}}source/" required pattern="^/.*/$" title="正确格式：/path/" disabled>
								</div>																					
								<div class="form-group">
									<label>排除文件<i class="fa fa-info-circle" data-toggle="tooltip" title="项目目录的相对路径"></i></label>
									<textarea class="form-control" rows="3" id="project_exclude" name="project_exclude"></textarea>
									<p class="help-block">例如：.git,data/upload</p>
								</div>

								

								<button type="reset" class="btn btn-default">撤销</button>
								<button type="button" class="btn btn-default"  onclick="addDeployProject(this,'audit')" >提交</button>
                            </form>
						</div>
						<!-- /.col-lg-6 (nested) -->
						<div class="hr hr32 hr-dotted"></div>
						<div class="col-lg-6">
							<legend>
								<i class="fa  fa-paper-plane-o"></i> 目标服务器
							</legend>
							<div class="form-group">
								<label><font color='red'>* </font>目标服务器</label> <br> 
								<select multiple class="form-control" name="server" id="server"  required> 
<!-- 									{% for ds in serverList %}
										<option name="server" value="{{ds.id}}">{{ds.ip}}</option> 
									{% endfor %} -->
								</select>
							</div>
							<div class="form-group">
								<label><font color='red'>* </font>用户<i class="fa fa-info-circle"
									data-toggle="tooltip" title="部署服务跟目标服务器都需要创建该用户"></i></label> <input
									class="form-control" id="project_user" required
									pattern="^\w+$" title="不要输入非法字符">
								<p class="help-block">例如：www</p>
							</div>
							<div class="form-group">
								<label><font color='red'>* </font>部署目录</label> <input class="form-control" id="dir" required pattern="^/.*/$" title="正确格式：/path/">
								<p class="help-block">例如：/var/www/project/</p>
							</div>
							<div class="form-group">
								<label>部署之后执行的命令</label>
								<textarea class="form-control" rows="3" id="project_remote_command" name="project_remote_command"></textarea>
								<p class="help-block">例如：service nginx restart && service httpd restart</p>
							</div>
						</div>
						<!-- /.col-lg-6 (nested) -->
						<div class="hr hr32 hr-dotted"></div>
						<div class="col-lg-6" id="extConfig" style="display: none;">
							<legend>
								<i class="fa  fa-gears"></i> 扩展配置
							</legend>
							<div class="form-group">
								<label><font color='red'>* </font>部署授权组<i class="fa fa-info-circle" data-toggle="tooltip" title="选择的用户组能够授权部署工单"></i></label> <br>
								<select class="form-control" name="project_audit_group" id="project_audit_group">
									<option name="project_audit_group" id="project_audit_group" selected="selected" value="0">选择一个授权组</option> 
									{% for ds in groupList %}
										<option name="project_audit_group"  value="{{ds.id}}">{{ds.name}}</option>
									{% endfor %}
								</select>
							</div>
						</div>
						</form>
					</div>
					<!-- /.row (nested) -->
				</div>
				<!-- /.panel-body -->
			</div>
			<!-- /.panel -->
		</div>
		<!-- /.col-lg-12 -->
	</div>
</div>

<script type="text/javascript">
{% if errorInfo %}
	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}
$(function () { $("[data-toggle='tooltip']").tooltip(); });

$(function(){
    $("#project_name").on("input",function(e){
    	$("#project_dir").attr("value",'{{project_dir}}release/'+e.delegateTarget.value+'/');
    	$("#project_repo_dir").attr("value",'{{project_dir}}source/'+e.delegateTarget.value+'/');
    	$("#dir").attr("value",'/var/www/'+e.delegateTarget.value+'/');
    });
    
});

var project_type = 'uncompile';
function setCompileMode(id){
	if (id=='compile'){
		document.getElementById("compile").style.display = "";
		project_type = 'compile';
	}
	else{
		document.getElementById("compile").style.display = "none";	
		project_type = 'uncompile';
	}
	
}



function setAceEditMode(model) {
	var editor = ace.edit("project_local_command");
	require("ace/ext/old_ie");
	var langTools = ace.require("ace/ext/language_tools");
	editor.setTheme("ace/theme/monokai");
	editor.insert("#!/bin/bash");
	editor.getSession().setMode("ace/mode/" + model);
	editor.setShowPrintMargin(false);
	editor.setOptions({
	    enableBasicAutocompletion: true,
	    enableSnippets: true,
	    enableLiveAutocompletion: true
	}); 
			 
};
setAceEditMode("sh");

function oBtProjectSelect(){
	   $('#project_service').removeAttr("disabled");
	   var obj = document.getElementById("project_id"); 
	   var index = obj.selectedIndex;
	   var projectId = obj.options[index].value; 
	   if ( projectId > 0){	 
			$.ajax({
				dataType: "JSON",
				url:'/api/project/'+ projectId + '/', //请求地址
				type:"GET",  //提交类似
				success:function(response){
					var binlogHtml = '<select class="form-control" name="project_service" id="project_service" onchange="javascript:oBtServiceSelect();" required><option selected="selected" name="project_service" value="">请选择业务类型</option>'
					var selectHtml = '';
					for (var i=0; i <response["service_assets"].length; i++){
						 selectHtml += '<option name="project_service" value="'+ response["service_assets"][i]["id"] +'">' + response["service_assets"][i]["service_name"] + '</option>' 
					};                        
					binlogHtml =  binlogHtml + selectHtml + '</select>';
					document.getElementById("project_service").innerHTML= binlogHtml;					
				},
			});	
	   }
	   else{
		   $('#project_service').attr("disabled",true);
	   }

}

function oBtServiceSelect(model,ids){
 	   $('#server').removeAttr("disabled");
	   var obj = document.getElementById("project_service"); 
	   var index = obj.selectedIndex;
	   var sId = obj.options[index].value; 
	   if ( sId  > 0){	 
			$.ajax({
				dataType: "JSON",
				url:'/assets_server/', //请求地址
				type:"POST",  //提交类似
				data:{
					"query":model,
					"id":sId
				},
				success:function(response){
					var binlogHtml = '<select multiple  name="server" id="server"  required>'
					var selectHtml = '';
					for (var i=0; i <response["data"].length; i++){
						 selectHtml += '<option name="server" value="'+ response["data"][i]["id"] +'">' + response["data"][i]["ip"] + ' | ' + response["data"][i]["project"] + ' | ' + response["data"][i]["service"] + '</option>' 
					};                        
					binlogHtml =  binlogHtml + selectHtml + '</select>';
					document.getElementById("server").innerHTML= binlogHtml;	
					$('#server').multiselect('destroy');
 				    $('#server').multiselect({
				        enableClickableOptGroups: true,
				        enableCollapsibleOptGroups: true,
				        includeSelectAllOption: true,
				       	enableFiltering: true,            
				    });	 						
				},
			});	
	   }
	   else{
		   $('#server option:selected').empty();
		   $('#server').attr("disabled",true);
	   }

}


function oBtEnvType() {
	   var obj = document.getElementById("project_env"); 
	   var index = obj.selectedIndex;
	   var value = obj.options[index].value; 
	   if (value=="uat"){
		   document.getElementById("extConfig").style.display = "";  	   
	   }
	   else {
		   document.getElementById("extConfig").style.display = "none";	
	   }
}
function oBtRepoType() {
	   var obj = document.getElementById("project_repertory"); 
	   var index = obj.selectedIndex;
	   var value = obj.options[index].value; 
	   if (value=="svn"){
		   document.getElementById("repo_type").style.display = "";  	   
	   }
	   else {
		   document.getElementById("repo_type").style.display = "none";	
	   }
}

function addDeployProject(obj) {	
	var btnObj = $(obj);
	var required = ["project_id","project_service","project_name","project_env","project_repertory","project_address","server","project_user","dir"];
	btnObj.attr('disabled',true);
		var form = document.getElementById('add_deploy_project');
		for (var i = 0; i < form.length; ++i) {
			var name = form[i].name;
			var value = form[i].value;	
			idx = $.inArray(name, required);						
			if (idx >= 0 && value.length == 0){
				window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
				btnObj.removeAttr('disabled');
				return false;
			};					
		};				
		var editor = ace.edit("project_local_command");
	    var project_local_command = editor.getSession().getValue(); 
	    var formData = new FormData();	
		var serverList = new Array();
		$("#server option:selected").each(function () {
			serverList.push($(this).val())
		})	    
	    formData.append('project_env',$('#project_env').val());	
	    formData.append('project_name',$('#project_name').val());	 
	    formData.append('project_address',$('#project_address').val());	
	    formData.append('project_user',$('#project_user').val());
	    formData.append('dir',$('#dir').val());		
	    formData.append('project_remote_command',$('#project_remote_command').val());
	    formData.append('project_exclude',$('#project_exclude').val());	
	    formData.append('project_dir',$('#project_dir').val());	
	    formData.append('project_repo_dir',$('#project_repo_dir').val());
	    formData.append('project_repo_user',$('#project_repo_user').val());	
	    formData.append('project_repo_passwd',$('#project_repo_passwd').val());
	    formData.append('project_audit_group',$('#project_audit_group  option:selected').val());	
	    formData.append('project_id',$('#project_id option:selected').val());
	    formData.append('project_service',$('#project_service option:selected').val());
	    formData.append('project_repertory',$('#project_repertory option:selected').val());
	    formData.append('project_model',$('#project_model option:selected').val());	
	    formData.append('server',serverList);	
	    formData.append('project_local_command',project_local_command);
	    formData.append('project_type',project_type);
		$.ajax({
/* 				dataType: "JSON", */
			url:'/deploy_add/', //请求地址
			type:"POST",  //提交类似
		    processData: false,
		    contentType: false,				
			data:formData,  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');				
				if (response["code"] == 200){
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
				}
				else {
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				};
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
	    	}
		});	
	}

</script>

{% endblock %}
